package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"short-vid-mgr/cache"
	"short-vid-mgr/models"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	var post []models.Post
	redis_data_key := "post_list"
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_data_key).Result()
	if redisData == "" {
		models.DB.Find(&post)
		jsonData, _ := json.Marshal(post)
		cache.Rdb.Set(cache.Ctx, redisData, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &post)
	}
	c.JSON(200, gin.H{
		"code": 0,
		"msg":  "查询成功",
		"data": post,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var post models.Post
	redis_data_key := "post_" + id
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_data_key).Result()
	if redisData == "" {
		models.DB.First(&post, id)
		jsonData, _ := json.Marshal(post)
		cache.Rdb.Set(cache.Ctx, redisData, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &post)
	}
	c.JSON(200, gin.H{
		"code": 0,
		"msg":  "查询成功",
		"data": post,
	})
	return
}
func Comm(c *gin.Context) {
	post_id, _ := strconv.Atoi(c.PostForm("post_id"))
	user_id, _ := strconv.Atoi(c.PostForm("user_id"))
	comm := models.Comm{
		PostId: post_id,
		UserId: user_id,
	}
	tx := models.DB.Begin()
	err := tx.Create(&comm).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "点赞失败",
		})
		return
	}
	var post models.Post
	err = tx.Where("id=?", post_id).First(&post).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "点赞文章不存在",
		})
		return
	}
	post.CommCount++
	tx.Select(&post)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "点赞成功",
	})
	tx.Commit()
	return
}
